package dao;

import entity.Alumno;
import entity.IEntity;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import vo.IValueObject;

/**
 *
 * @author Alexander
 */
public class AlumnoDAO implements IDAO {

    @Override
    public void persist(IEntity entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public IValueObject find(Object id, EntityManager em) {
        Alumno a = (Alumno)em.find(Alumno.class, (String) id);
        if (a!=null) {
            return a.toVo();
        } else {
            return null;
        }
    }

    @Override
    public void update(IEntity entity, EntityManager em) {
        em.merge(entity);
    }

    public Alumno login(Alumno entity, EntityManager em) {
        Alumno alumno = null;
        Query q = em.createQuery("SELECT u FROM Alumno u "
                + "WHERE u.username LIKE :username "
                + "AND u.password LIKE :password").setParameter("username", entity.getUsername()).setParameter("password", entity.getPassword());

        try {
            alumno = (Alumno) q.getSingleResult();
        } catch (Exception e)  {
            System.out.println(e.getMessage());
        }
        return alumno;
    }

    @Override
    public void delete(Object id, EntityManager em) {
        Alumno alumno = em.getReference(Alumno.class, (String) id);
        em.remove(alumno);
    }
    
    /**
     * Busca un usuario basandose en la IP
     * @param ip Ip del usuario
     * @param em Controlador de transacciones
     * @return El usuario buscado
     */
    public IValueObject FindByIP(Object ip, EntityManager em){
        Alumno a = null;
        Query q = em.createQuery("SELECT u FROM Alumno u "
                + "WHERE u.usuarioActivo = :usuario").setParameter("usuario", (String)ip);
        
        try{
            a = (Alumno) q.getSingleResult();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
        return a.toVo();
    }

    @Override
    public List<IValueObject> getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Alumno.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    }
}
